class VehicleMailer < ActionMailer::Base
  default :from => "notifications@example.com"
 
  def send_vehicle_info(destinations, vehicles)
    destinations = [destinations].flatten
    @vehicles = []
    vehicles.each do |vehicle|
      
      similar_vehicles = []
      similar_vehicles << [VehicleResult.find_by_year_and_name(vehicle[:vehicle].year, vehicle[:vehicle].name)] 
      similar_vehicles << [VehicleResult.find_by_year_and_name(vehicle[:vehicle].year - 1, vehicle[:vehicle].name)]
      similar_vehicles << [VehicleResult.find_by_year_and_name(vehicle[:vehicle].year + 1, vehicle[:vehicle].name)]
      similar_vehicles.flatten!
      similar_vehicles.delete nil
      
      average_price = 0
      average_km = 0
      
      if not similar_vehicles.empty?
        price_array = similar_vehicles.map { |v| v.price } 
        km_array = similar_vehicles.map { |v| v.km }
        average_price = (price_array.sum.to_f/price_array.size).to_i
        average_km = (km_array.sum.to_f/km_array.size).to_i
      end
      sample_size = similar_vehicles.size
      
      @vehicles << {
        :info => VehicleResult.find(vehicle[:vehicle].id), 
        :old_price => (vehicle[:changes].nil? ? nil : vehicle[:changes][:old_price]),
        :average_price => average_price,
        :average_km => average_km  ,
        :sample_size => sample_size      
        }
    end
    
    puts "Sending Results!" 
    
    mail(:to => destinations,
         :subject => ("Vehicle Updates!"))
  end
end

